import "package:craze/common/index.dart";
import "package:craze/models/index.dart";
import "package:craze/services/index.dart";
import "package:craze/stores/index.dart";
import "package:flutter/material.dart";
import "package:flutter_screenutil/flutter_screenutil.dart";
import "package:google_fonts/google_fonts.dart";
import "package:flutter_swiper_view/flutter_swiper_view.dart";
import "package:flutter_mobx/flutter_mobx.dart";
import "package:go_router/go_router.dart";
import "package:shimmer/shimmer.dart";
import "image_preview_page.dart";

class OceanView extends StatefulWidget {
  const OceanView({super.key});

  @override
  State<OceanView> createState() => _OceanViewState();
}

class _OceanViewState extends State<OceanView> {
  int _currentIndex = 0;
  late SwiperController _swiperController;

  // 获取store
  final ScanResultStore _scanResultStore = getIt<ScanResultStore>();
  final MarineProtectionStore _marineProtectionStore =
      getIt<MarineProtectionStore>();
  final UserService _userService = getIt<UserService>();
  final AuthStore _authStore = getIt<AuthStore>();
  final CollectionStore _collectionStore = getIt<CollectionStore>();

  // 缓存用户信息，避免重复加载
  final Map<String, _UserDisplayInfo> _userInfoCache = {};

  @override
  void initState() {
    super.initState();
    _swiperController = SwiperController();

    // 加载数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadData();
    });
  }

  // 加载数据
  Future<void> _loadData() async {
    // 设置loading状态
    _scanResultStore.isLoading = true;
    _marineProtectionStore.isLoading = true;

    // 添加延迟以便观察骨架屏
    await Future.delayed(const Duration(seconds: 1));

    // 加载扫描结果
    await _scanResultStore.loadScanResults();

    // 预加载所有用户信息
    _preloadUserInfo();

    // 添加延迟以便观察骨架屏
    await Future.delayed(const Duration(seconds: 1));

    // 加载海洋保护活动
    await _marineProtectionStore.loadActivities();
  }

  // 预加载所有用户信息
  void _preloadUserInfo() {
    for (var result in _scanResultStore.scanResults) {
      final user = _userService.getUserById(result.userId);
      if (user != null) {
        _userInfoCache[result.userId] = _UserDisplayInfo(
          name: user.name,
          avatar: user.avatar.isNotEmpty ? user.avatar : MyImages.touxiang1,
        );
      } else {
        _userInfoCache[result.userId] = _UserDisplayInfo(
          name: 'Unknown',
          avatar: '',
        );
      }
    }
  }

  // 获取用户显示信息
  _UserDisplayInfo _getUserDisplayInfo(String userId) {
    // 从缓存获取
    if (_userInfoCache.containsKey(userId)) {
      return _userInfoCache[userId]!;
    }

    // 如果缓存中没有，立即获取并缓存
    final user = _userService.getUserById(userId);
    final info =
        user != null
            ? _UserDisplayInfo(
              name: user.name,
              avatar: user.avatar.isNotEmpty ? user.avatar : MyImages.touxiang1,
            )
            : _UserDisplayInfo(name: 'Unknown', avatar: '');

    _userInfoCache[userId] = info;
    return info;
  }

  // 检查扫描结果是否被收藏
  bool _isScanResultFavorited(ScanResultModel result) {
    // 如果用户未登录，始终显示为未收藏状态
    if (!_authStore.isLoggedIn) {
      return false;
    }
    // 否则返回实际收藏状态
    return result.isFavorite;
  }

  @override
  void dispose() {
    _swiperController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.commonBg),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 标题
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20.w),
                child: Row(
                  children: [
                    Text(
                      'Ai species identification',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 22.sp,
                        fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                        fontWeight: FontWeight.w400,
                        height: 1.36,
                      ),
                    ),
                    const Spacer(),
                    GestureDetector(
                      onTap: () {
                        // 检查用户是否登录
                        if (!_authStore.isLoggedIn) {
                          // 显示登录提示对话框
                          LoginDialog.show(
                            context,
                            title: 'Login Required',
                            description:
                                'You need to login to use the AI species identification feature.',
                          );
                          return;
                        }

                        // 已登录，导航到扫描页面
                        GoRouter.of(context).push(AppRouter.scan);
                      },
                      child: Icon(
                        MyIcons.iconScan,
                        color: Colors.white,
                        size: 28.sp,
                      ),
                    ),
                  ],
                ),
              ),

              SizedBox(height: 30.h),

              // 用户扫描结果列表
              SizedBox(
                height: 220.h,
                child: Observer(
                  builder: (_) {
                    if (_scanResultStore.isLoading) {
                      return _buildScanResultShimmer();
                    }

                    if (_scanResultStore.scanResults.isEmpty) {
                      return Center(
                        child: Text(
                          'No scan results available',
                          style: TextStyle(color: Colors.white),
                        ),
                      );
                    }

                    return Swiper(
                      controller: _swiperController,
                      itemBuilder: (BuildContext context, int index) {
                        return _buildScanResultCard(
                          _scanResultStore.scanResults[index],
                        );
                      },
                      itemCount: _scanResultStore.scanResults.length,
                      viewportFraction: 0.53,
                      scale: 0.85,
                      layout: SwiperLayout.DEFAULT,
                      loop: true,
                      index: _currentIndex,
                      autoplay: true,
                      autoplayDelay: 3000,
                      onIndexChanged: (int index) {
                        setState(() {
                          _currentIndex = index;
                        });
                      },
                    );
                  },
                ),
              ),

              SizedBox(height: 28.h),

              // 标题
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20.w),
                child: Text(
                  'Marine protection',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 22.sp,
                    fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                    fontWeight: FontWeight.w400,
                    height: 1.36,
                  ),
                ),
              ),

              // 保护海洋活动列表
              SizedBox(height: 20.h),

              Expanded(
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 20.w),
                  child: Observer(
                    builder: (_) {
                      if (_marineProtectionStore.isLoading) {
                        return _buildProtectionActivitiesShimmer();
                      }

                      if (_marineProtectionStore.activities.isEmpty) {
                        return Center(
                          child: Text(
                            'No marine protection activities available',
                            style: TextStyle(color: Colors.white),
                          ),
                        );
                      }

                      return ListView.builder(
                        itemCount: _marineProtectionStore.activities.length,
                        itemBuilder: (context, index) {
                          final activity =
                              _marineProtectionStore.activities[index];
                          return Padding(
                            padding: EdgeInsets.only(bottom: 20.w),
                            child: GestureDetector(
                              onTap: () {
                                // 跳转到活动详情页，传递活动ID
                                GoRouter.of(context).push(
                                  "${AppRouter.protection}?activityId=${activity.id}",
                                );
                              },
                              child: AspectRatio(
                                aspectRatio: 374 / 184.39,
                                child: Image.asset(
                                  activity.imageUrl,
                                  fit: BoxFit.fill,
                                  errorBuilder: (context, error, stackTrace) {
                                    return Container(
                                      decoration: BoxDecoration(
                                        color: const Color(0xFF262C3A),
                                        borderRadius: BorderRadius.circular(
                                          12.r,
                                        ),
                                      ),
                                      child: Center(
                                        child: Text(
                                          activity.title,
                                          style: TextStyle(color: Colors.white),
                                        ),
                                      ),
                                    );
                                  },
                                ),
                              ),
                            ),
                          );
                        },
                      );
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 扫描结果骨架屏
  Widget _buildScanResultShimmer() {
    return Swiper(
      itemBuilder: (BuildContext context, int index) {
        return Shimmer.fromColors(
          baseColor: const Color(0xFF262C3A),
          highlightColor: const Color(0xFF3A4356),
          child: Container(
            decoration: BoxDecoration(
              color: const Color(0xFF262C3A),
              borderRadius: BorderRadius.circular(12.r),
            ),
            padding: EdgeInsets.all(10.r),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 图片区域骨架
                Expanded(
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 左侧图片骨架
                      ClipRRect(
                        borderRadius: BorderRadius.circular(12.r),
                        child: Container(
                          width: 140.w,
                          height: double.infinity,
                          color: Colors.white,
                        ),
                      ),
                      SizedBox(width: 10.w),
                      // 右侧信息区域骨架
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Container(
                              width: 40.w,
                              height: 12.h,
                              color: Colors.white,
                            ),
                            SizedBox(height: 8.h),
                            Container(
                              width: 30.w,
                              height: 20.h,
                              color: Colors.white,
                            ),
                            SizedBox(height: 16.h),
                            Container(
                              width: 37.w,
                              height: 37.w,
                              decoration: const BoxDecoration(
                                color: Colors.white,
                                shape: BoxShape.circle,
                              ),
                            ),
                            SizedBox(height: 8.h),
                            Container(
                              width: 60.w,
                              height: 12.h,
                              color: Colors.white,
                            ),
                            const Spacer(),
                            Container(
                              width: 40.w,
                              height: 40.w,
                              decoration: const BoxDecoration(
                                color: Colors.white,
                                shape: BoxShape.circle,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 8.h),
                // 标题骨架
                Container(width: 120.w, height: 14.h, color: Colors.white),
              ],
            ),
          ),
        );
      },
      itemCount: 3,
      viewportFraction: 0.53,
      scale: 0.85,
      layout: SwiperLayout.DEFAULT,
      loop: true,
      autoplay: false,
    );
  }

  // 海洋保护活动骨架屏
  Widget _buildProtectionActivitiesShimmer() {
    return ListView.builder(
      itemCount: 4,
      itemBuilder: (context, index) {
        return Padding(
          padding: EdgeInsets.only(bottom: 20.w),
          child: Shimmer.fromColors(
            baseColor: const Color(0xFF262C3A),
            highlightColor: const Color(0xFF3A4356),
            child: AspectRatio(
              aspectRatio: 374 / 184.39,
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(12.r),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildScanResultCard(ScanResultModel result) {
    // 格式化日期为月份和日
    final monthNames = [
      'Jan',
      'Feb',
      'Mar',
      'Apr',
      'May',
      'Jun',
      'Jul',
      'Aug',
      'Sep',
      'Oct',
      'Nov',
      'Dec',
    ];
    final month = monthNames[result.scanDate.month - 1];
    final day = result.scanDate.day.toString().padLeft(2, '0');

    // 从缓存获取用户信息
    final userInfo = _getUserDisplayInfo(result.userId);

    return Container(
      decoration: BoxDecoration(
        color: const Color(0xFF262C3A),
        borderRadius: BorderRadius.circular(12.r),
      ),
      padding: EdgeInsets.all(10.r),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 第一排：图片和信息列
          Expanded(
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 左侧图片
                ClipRRect(
                  borderRadius: BorderRadius.circular(12.r),
                  child: GestureDetector(
                    onTap: () {
                      // 点击图片，显示预览
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder:
                              (context) => ImagePreviewPage(
                                imagePath: result.imageUrl,
                                isAsset: result.imageUrl.startsWith('assets/'),
                                heroTag: 'scan_result_${result.id}',
                              ),
                        ),
                      );
                    },
                    child: Hero(
                      tag: 'scan_result_${result.id}',
                      child: SizedBox(
                        width: 140.w,
                        height: double.infinity,
                        child: Image.asset(
                          result.imageUrl,
                          fit: BoxFit.cover,
                          errorBuilder: (context, error, stackTrace) {
                            return Container(
                              color: const Color(0xFF1E1F31),
                              child: Center(
                                child: Icon(
                                  Icons.image_not_supported,
                                  color: Colors.white,
                                  size: 40.sp,
                                ),
                              ),
                            );
                          },
                        ),
                      ),
                    ),
                  ),
                ),

                SizedBox(width: 10.w),

                // 右侧信息列
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      // 日期
                      Text(
                        month,
                        style: TextStyle(
                          color: Colors.white.withAlpha(128),
                          fontSize: 12.sp,
                          fontWeight: FontWeight.w400,
                          fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                          height: 1.17,
                        ),
                      ),
                      Text(
                        day,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 20.sp,
                          fontWeight: FontWeight.w400,
                          fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                          height: 1.3,
                        ),
                      ),

                      SizedBox(height: 16.h),

                      // 用户信息，使用缓存的数据
                      GestureDetector(
                        onTap: () {
                          GoRouter.of(context).push(
                            AppRouter.otherProfile,
                            extra: {'userId': result.userId},
                          );
                        },
                        child: CircleAvatar(
                          radius: 18.5.r,
                          backgroundImage:
                              userInfo.avatar.isNotEmpty
                                  ? AssetImage(userInfo.avatar)
                                  : null,
                          backgroundColor:
                              userInfo.avatar.isEmpty
                                  ? const Color(0xFF1E1F31)
                                  : null,
                          child:
                              userInfo.avatar.isEmpty
                                  ? Icon(
                                    Icons.person,
                                    color: Colors.white,
                                    size: 24.sp,
                                  )
                                  : null,
                        ),
                      ),
                      SizedBox(height: 4.h),
                      Text(
                        userInfo.name,
                        style: TextStyle(
                          color: Colors.white.withAlpha(128),
                          fontSize: 12.sp,
                          fontWeight: FontWeight.w400,
                          fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                        ),
                        textAlign: TextAlign.center,
                      ),

                      const Spacer(),

                      // 收藏按钮
                      GestureDetector(
                        onTap: () async {
                          // 检查用户是否登录
                          if (!_authStore.isLoggedIn) {
                            // 显示登录提示对话框
                            await LoginDialog.show(
                              context,
                              title: 'Login Required',
                              description:
                                  'You need to login to favorite this scan result.',
                            );
                            return;
                          }

                          // 切换收藏状态
                          await _scanResultStore.toggleFavorite(result.id);

                          // 同步到用户收藏列表
                          await _collectionStore.toggleScanResultCollection(
                            result.id,
                          );

                          // 强制刷新UI以显示最新收藏状态
                          setState(() {});
                        },
                        child: Container(
                          padding: EdgeInsets.all(8.r),
                          decoration: BoxDecoration(
                            color: MyColors.iconDark,
                            shape: BoxShape.circle,
                          ),
                          child: Icon(
                            _isScanResultFavorited(result)
                                ? Icons.star
                                : Icons.star_border,
                            color:
                                _isScanResultFavorited(result)
                                    ? Colors.amber
                                    : Colors.white,
                            size: 24.sp,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),

          SizedBox(height: 8.h),

          // 第二排：详情文字
          Text(
            "${userInfo.name} just scan the photo.",
            style: TextStyle(
              color: Colors.white,
              fontSize: 14.sp,
              fontWeight: FontWeight.w600,
              fontFamily: GoogleFonts.inter().fontFamily,
            ),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ],
      ),
    );
  }
}

// 用户显示信息缓存类
class _UserDisplayInfo {
  final String name;
  final String avatar;

  _UserDisplayInfo({required this.name, required this.avatar});
}
